//
//  CNBBSDetailCell.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/7/17.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNBBSDetailCell.h"
#import <WebKit/WebKit.h>
#import "YYPhotoBrowseView.h"
#import "CNBBSDetailViewController.h"
#import "CNBBSBrowserToolViewHandler.h"
#import <CNBaseTool/CNCategoryHeader.h>
#import <CNBaseViewTool/CNViewConst.h>
#import <YBImageBrowser/YBImageBrowser.h>
#import <CNBaseViewTool/YYPhotoBrowseView.h>


@interface CNBBSDetailCell ()<DTAttributedTextContentViewDelegate,DTLazyImageViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIButton *headImageBtn;

@property (nonatomic, strong) UILabel *nickNameLb;

@property (nonatomic, strong) UILabel *timeLb;

@property (nonatomic, strong) UIButton *replyBtn;

@property (nonatomic, strong) UIButton *reportBtn;

@property (nonatomic, strong) UIButton *diggBtn;

@property (nonatomic, strong) UIButton *shieldBtn;

@property (nonatomic, strong) UILabel *diggLb;

@property (nonatomic, strong ) UILabel *scoreLb;


@property (strong, nonatomic)  DTAttributedLabel *attributedLabel;

@property (nonatomic, assign) CGRect viewMaxRect;

@end

@implementation CNBBSDetailCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(UIButton *)headImageBtn
{
    if (!_headImageBtn) {
        _headImageBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _headImageBtn.layer.allowsEdgeAntialiasing = YES;
        [_headImageBtn setEnlargeEdge:15];
        [self.contentView addSubview:_headImageBtn];
        [_headImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.top.mas_equalTo(12);
            make.size.mas_equalTo(CGSizeMake(28, 28));
        }];
        
        @weakify(self);
        [_headImageBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if (self.delegate && [self.delegate respondsToSelector:@selector(cellDidClickHeadImage:)])
            {
                [self.delegate cellDidClickHeadImage:self];
            }
            
        } forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _headImageBtn;
}

-(UILabel *)nickNameLb
{
    if (!_nickNameLb) {
        _nickNameLb = [[UILabel alloc]init];
        _nickNameLb.theme_textColor = focusLogingTextColorPicker;
        _nickNameLb.font = [UIFont systemFontOfSize:11];
        [self.contentView addSubview:_nickNameLb];
        [_nickNameLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.headImageBtn);
            make.left.mas_equalTo(self.headImageBtn.mas_right).mas_equalTo(6);
        }];
    }
    return _nickNameLb;
}

-(UILabel *)floorLb
{
    if (!_floorLb) {
        _floorLb = [[UILabel alloc]init];
        _floorLb.theme_textColor = cellDesTitleTextColorPicker;
        _floorLb.font = [UIFont systemFontOfSize:11];
        [self.contentView addSubview:_floorLb];
        [_floorLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.nickNameLb);
            make.centerY.mas_equalTo(self.nickNameLb);
            make.left.mas_equalTo(self.nickNameLb.mas_right).mas_equalTo(12);
            make.right.mas_lessThanOrEqualTo(self.scoreLb.mas_left).mas_offset(-16);
        }];
    }
    return _floorLb;
}

-(UILabel *)scoreLb
{
    if (!_scoreLb) {
        _scoreLb = [[UILabel alloc]init];
        _scoreLb.theme_textColor = scoreTextColorPicker;
        _scoreLb.font = [UIFont systemFontOfSize:11];
        [self.contentView addSubview:_scoreLb];
        [_scoreLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.nickNameLb);
            make.right.mas_equalTo(-16);
        }];
    }
    return _scoreLb;
}

//懒加载创建
- (DTAttributedLabel *)attributedLabel{
    if (_attributedLabel == nil) {
        _attributedLabel = [[DTAttributedLabel alloc] initWithFrame:CGRectZero];
        _attributedLabel.delegate = self;
        _attributedLabel.theme_backgroundColor = pageBGColorPicker;
        [self.contentView addSubview:_attributedLabel];
        [_attributedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.nickNameLb.mas_bottom).mas_equalTo(4);
            make.left.mas_equalTo(self.nickNameLb);
            make.right.mas_equalTo(-16);
        }];
    }
    return _attributedLabel;
}

-(UILabel *)timeLb
{
    if (!_timeLb) {
        _timeLb = [[UILabel alloc]init];
        _timeLb.theme_textColor = cellDesTitleTextColorPicker;
        _timeLb.font = [UIFont systemFontOfSize:11];
        [self.contentView addSubview:_timeLb];
        [_timeLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.nickNameLb);
            make.top.mas_equalTo(self.attributedLabel.mas_bottom).mas_equalTo(8);
        }];
        UIView *spaceView = [[UIView alloc]init];
        spaceView.theme_backgroundColor = searchPageBGColorPicker;
        [self.contentView addSubview:spaceView];
        [spaceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.timeLb.mas_bottom).mas_equalTo(12);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.height.mas_equalTo(8);
        }];
    }
    return _timeLb;
}

-(UIButton *)replyBtn
{
    if (!_replyBtn) {
        _replyBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_replyBtn setEnlargeEdge:15];
        [_replyBtn theme_setTitleColor:cellDesTitleTextColorPicker forState:(UIControlStateNormal)];
        [_replyBtn theme_setTitleColor:cellDesTitleTextColorPicker forState:(UIControlStateHighlighted)];
        [_replyBtn setTitle:@"回复" forState:(UIControlStateNormal)];
        [_replyBtn setTitle:@"回复" forState:(UIControlStateHighlighted)];
        _replyBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        [self.contentView addSubview:_replyBtn];
        [_replyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.timeLb.mas_right).mas_equalTo(12);
            make.centerY.mas_equalTo(self.timeLb);
        }];
        
        @weakify(self);
        [_replyBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if (self.delegate && [self.delegate respondsToSelector:@selector(cellDidClickReplyButton:)])
            {
                [self.delegate cellDidClickReplyButton:self];
            }
            
        } forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _replyBtn;
}

-(UILabel *)diggLb
{
    if (!_diggLb) {
        _diggLb = [[UILabel alloc]init];
        _diggLb.theme_textColor = readAndTimeTextColorPicker;
        _diggLb.font = [UIFont systemFontOfSize:12];
        [self.contentView addSubview:_diggLb];
        [_diggLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-16);
            make.centerY.mas_equalTo(self.timeLb);
        }];
    }
    return _diggLb;
}

-(UIButton *)diggBtn
{
    if (!_diggBtn) {
        _diggBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_diggBtn setEnlargeEdge:15];
        [self.contentView addSubview:_diggBtn];
        [_diggBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.diggLb.mas_left).mas_equalTo(-2);
            make.centerY.mas_equalTo(self.diggLb);
            make.size.mas_equalTo(CGSizeMake(16, 16));
        }];
        @weakify(self);
        [_diggBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if (self.delegate && [self.delegate respondsToSelector:@selector(cellDidClickDiggButton:)])
            {
                [self.delegate cellDidClickDiggButton:self];
            }
            
        } forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _diggBtn;
}

-(UIButton *)reportBtn
{
    if (!_reportBtn) {
        _reportBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_reportBtn setEnlargeEdge:15];
        [_reportBtn theme_setTitleColor:cellDesTitleTextColorPicker forState:(UIControlStateNormal)];
        [_reportBtn theme_setTitleColor:cellDesTitleTextColorPicker forState:(UIControlStateHighlighted)];
        [_reportBtn setTitle:@"举报" forState:(UIControlStateNormal)];
        [_reportBtn setTitle:@"举报" forState:(UIControlStateHighlighted)];
        _reportBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        [self.contentView addSubview:_reportBtn];
        [_reportBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.diggBtn.mas_left).mas_equalTo(-20);
            make.centerY.mas_equalTo(self.timeLb);
        }];
        
        @weakify(self);
        [_reportBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if (self.delegate && [self.delegate respondsToSelector:@selector(cellDidClickReportButton:)])
            {
                [self.delegate cellDidClickReportButton:self];
            }
            
        } forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _reportBtn;
}

-(UIButton *)shieldBtn
{
    if (!_shieldBtn) {
        _shieldBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_shieldBtn setEnlargeEdge:15];
        [_shieldBtn theme_setTitleColor:cellDesTitleTextColorPicker forState:(UIControlStateNormal)];
        [_shieldBtn theme_setTitleColor:cellDesTitleTextColorPicker forState:(UIControlStateHighlighted)];
        [_shieldBtn setTitle:@"屏蔽" forState:(UIControlStateNormal)];
        [_shieldBtn setTitle:@"屏蔽" forState:(UIControlStateHighlighted)];
        _shieldBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        [self.contentView addSubview:_shieldBtn];
        [_shieldBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.reportBtn.mas_left).mas_equalTo(-20);
            make.centerY.mas_equalTo(self.timeLb);
        }];
        
        @weakify(self);
        [_shieldBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if (self.delegate && [self.delegate respondsToSelector:@selector(cellDidClickShieldButton:)])
            {
                [self.delegate cellDidClickShieldButton:self];
            }
            
        } forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _shieldBtn;
}


#pragma mark - 获取导航控制器

- (UIViewController *)currentViewController
{
    UIResponder *next = self.nextResponder;
    do {
        //判断响应者是否为视图控制器
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = next.nextResponder;
    } while (next != nil);
    
    return nil;
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.theme_backgroundColor = pageBGColorPicker;
        self.contentView.theme_backgroundColor = pageBGColorPicker;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.replyBtn.hidden = NO;
        self.reportBtn.hidden = NO;
        if ([CNViewConst csdnIsAudit]) {
            self.shieldBtn.hidden = NO;
        }else{
            self.shieldBtn.hidden = YES;
        }
    }
    return self;
}

-(void)setHeadUrl:(NSString *)headUrl
{
    _headUrl = headUrl;
    @weakify(self);
    [self.headImageBtn yy_setBackgroundImageWithURL:[NSURL URLWithString:headUrl] forState:(UIControlStateNormal) placeholder:[UIImage imageNamed:@"headImage"] options:kNilOptions progress:nil transform:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        @strongify(self);
        if (!error) {
            image = [UIImage imageWithRoundCorner:image cornerRadius:24 size:CGSizeMake(48, 48)];
            [self.headImageBtn setBackgroundImage:image forState:(UIControlStateNormal)];
        }
    }];
}

-(void)setNickName:(NSString *)nickName
{
    _nickName = nickName;
    self.nickNameLb.text = nickName;
}

-(void)setFloorText:(NSString *)floorText
{
    _floorText = floorText;
    self.floorLb.text = floorText;
}

-(void)setTimeText:(NSString *)timeText
{
    _timeText = timeText;
    self.timeLb.text = timeText;
}

-(void)setScore:(NSString *)score
{
    _score = score;
    self.scoreLb.text = score;
}

-(void)setIsScore:(BOOL)isScore
{
    if (isScore)
    {
        self.scoreLb.hidden = NO;
    }
    else
    {
        self.scoreLb.hidden = YES;
    }
}

-(void)setIsDigg:(BOOL)isDigg
{
    _isDigg = isDigg;
    if (!isDigg) {
        [_diggBtn setImage:[UIImage imageNamed:@"bbs_zan"] forState:UIControlStateNormal];
        [_diggBtn setImage:[UIImage imageNamed:@"bbs_zan"] forState:UIControlStateHighlighted];
        self.diggLb.theme_textColor = cellDesTitleTextColorPicker;
    }else{
        [_diggBtn setImage:[UIImage imageNamed:@"bbs_zan-red"] forState:UIControlStateNormal];
        [_diggBtn setImage:[UIImage imageNamed:@"bbs_zan-red"] forState:UIControlStateHighlighted];
        self.diggLb.theme_textColor = naviBGColorPicker;
    }
}

-(void)setDiggCount:(NSString *)diggCount
{
    
    if ([diggCount isEqualToString:@"0"])
    {
        diggCount = @"赞";
    }
    _diggCount = diggCount;
    self.diggLb.text = diggCount;
    
}

-(void)setHtmlText:(NSString *)htmlText
{
    _htmlText = [CNViewConst convertHtmlFromBodyString:htmlText fontSize:14 fitImageSize:NO];
    
    self.viewMaxRect =  CGRectMake(50, 32, kWindowW-66, CGFLOAT_HEIGHT_UNKNOWN);
    ////    //创建控件，显示富文本
    CGSize textSize = [self getAttributedTextHeightHtml:_htmlText with_viewMaxRect:_viewMaxRect];
   
    self.attributedLabel.attributedString = [self getAttributedStringWithHtml:_htmlText];
    self.attributedLabel.frame = CGRectMake(_viewMaxRect.origin.x, _viewMaxRect.origin.y, _viewMaxRect.size.width, textSize.height);
    [self.attributedLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(textSize.height);
    }];
    [self.attributedLabel relayoutText];
}

- (BOOL)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView shouldDrawBackgroundForTextBlock:(DTTextBlock *)textBlock frame:(CGRect)frame context:(CGContextRef)context forLayoutFrame:(DTCoreTextLayoutFrame *)layoutFrame
{
    
    if(textBlock.padding.top==5)
    {
        if ([CNThemesManager isNight])
        {
            UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:0];
            CGRect blockquoteFrame=CGRectInset(frame, 1, 1);
            CGColorRef borderColor= [UIColor clearColor].CGColor;
            CGContextAddPath(context, roundedRect.CGPath);
            CGContextSetStrokeColorWithColor(context, borderColor);
            CGContextSetFillColorWithColor(context, [UIColor colorFromHexCode:@"#34373D" andAlpha:1].CGColor);
            CGContextStrokePath(context);
            CGContextFillRect(context,blockquoteFrame);
        }
        else
        {
            UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:0];
            CGRect blockquoteFrame=CGRectInset(frame, 1, 1);
            CGColorRef borderColor= [UIColor colorFromHexCode:@"#D3E5F0" andAlpha:1].CGColor;
            CGContextAddPath(context, roundedRect.CGPath);
            CGContextSetStrokeColorWithColor(context, borderColor);
            CGContextSetFillColorWithColor(context, [UIColor colorFromHexCode:@"#F5FBFF" andAlpha:1].CGColor);
            CGContextStrokePath(context);
            CGContextFillRect(context,blockquoteFrame);
        }
    }
    return NO; // draw standard background
}


//#pragma mark - Delegate：DTAttributedTextContentViewDelegate
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame
{
    
    if ([attachment isKindOfClass:[DTImageTextAttachment class]])
    {
        // if the attachment has a hyperlinkURL then this is currently ignored
        YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithFrame:frame];
        // url for deferred loading
        imageView.yy_imageURL = attachment.contentURL;

        if(!CGSizeEqualToSize(attachment.originalSize, CGSizeMake(25, 25)))
        {
            // if there is a hyperlink then add a link button on top of this image
            if (attachment.hyperLinkURL)
            {
                // NOTE: this is a hack, you probably want to use your own image view and touch handling
                // also, this treats an image with a hyperlink by itself because we don't have the GUID of the link parts
                imageView.userInteractionEnabled = YES;
                DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:imageView.bounds];
                button.URL = attachment.hyperLinkURL;
                button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
                button.GUID = attachment.hyperLinkGUID;
                button.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
                // use normal push action for opening URL
                [button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];
                
                // demonstrate combination with long press
                [imageView addSubview:button];
            }
            else
            {
                imageView.userInteractionEnabled = YES;
                UITapGestureRecognizer * onetap =[[UITapGestureRecognizer alloc] bk_initWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
                    
//                    YBImageBrowseCellData *data = [YBImageBrowseCellData new];
//                    data.url = attachment.contentURL;
//                    data.sourceObject = (YYAnimatedImageView *)sender.view;;
                    YBIBImageData *data = [YBIBImageData new];
                    data.imageURL = attachment.contentURL;
                    data.projectiveView = (YYAnimatedImageView *)sender.view;;

                    YBImageBrowser *browser = [YBImageBrowser new];
                    browser.dataSourceArray = @[data];
                    browser.toolViewHandlers = @[CNBBSBrowserToolViewHandler.new];
                    [browser show];
                }];
                onetap.numberOfTapsRequired = 1;
                onetap.numberOfTouchesRequired = 1;
                [imageView addGestureRecognizer:onetap];
            }
            
        }
        return imageView;
    }
    
    else if ([attachment isKindOfClass:[DTObjectTextAttachment class]])
    {
        // somecolorparameter has a HTML color
        NSString *colorName = [attachment.attributes objectForKey:@"somecolorparameter"];
        UIColor *someColor = DTColorCreateWithHTMLName(colorName);
        
        UIView *someView = [[UIView alloc] initWithFrame:frame];
        someView.backgroundColor = someColor;
        someView.layer.borderWidth = 1;
        someView.layer.borderColor = [UIColor blackColor].CGColor;
        //        someView.layer.borderColor = [UIColor blueColor].CGColor;
        someView.accessibilityLabel = colorName;
        someView.isAccessibilityElement = YES;
        
        return someView;
    }
    
    
    return nil;
}

-(UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttributedString:(NSAttributedString *)string frame:(CGRect)frame
{
    NSDictionary *attributes = [string attributesAtIndex:0 effectiveRange:NULL];
    
    NSURL *URL = [attributes objectForKey:DTLinkAttribute];
    NSString *identifier = [attributes objectForKey:DTGUIDAttribute];
    
    
    DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:frame];
    button.URL = URL;
    button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
    button.GUID = identifier;
    
    // use normal push action for opening URL
    [button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

//点击链接
- (void)linkPushed:(DTLinkButton *)button
{
    NSURL *url = button.URL;
    if ([url.absoluteString hasPrefix:@"//img"]) {
        YYPhotoGroupItem *item = [[YYPhotoGroupItem alloc]init];
        item.thumbView = self.contentView;
        item.thumbView = (YYAnimatedImageView *)button.superview;
        item.largeImageURL = url;
        YYPhotoBrowseView *groupView = [[YYPhotoBrowseView alloc]initWithGroupItems:@[item]];
        [groupView presentFromImageView:(YYAnimatedImageView *)button.superview toContainer:[UIApplication sharedApplication].keyWindow animated:YES completion:nil];
        return;
    }
    
    UIApplication *app = [UIApplication sharedApplication];
    
    if ([url.absoluteString containsString:@"itunes.apple.com"]){
        if ([app canOpenURL:url]){
            [app openURL:url];
            
            return;
        }
    }
    
    if ([url.absoluteString containsString:@"//bbs.csdn.net/topics/"])
    {
        CNBBSDetailViewController *vc = [[CNBBSDetailViewController alloc]init];
        vc.topicId = [[url.absoluteString componentsSeparatedByString:@"/"] lastObject];
        [[self currentViewController].navigationController pushViewController:vc animated:YES];
        return;
    }
#warning Route跳转
    [CNRouteTool routeUrl:url.absoluteString navigationVc:[self currentViewController].navigationController refer:@"bbs" trackingCode:@"" urlParams:@{} vipReferrer:@"论坛" exts:@{}];
    
}



#pragma mark - private Methods
//使用HtmlString,和最大左右间距，计算视图的高度
- (CGSize)getAttributedTextHeightHtml:(NSString *)htmlString with_viewMaxRect:(CGRect)_viewMaxRect
{
    //获取富文本
    NSAttributedString *attributedString =  [self getAttributedStringWithHtml:htmlString];
    //获取布局器
    DTCoreTextLayouter *layouter = [[DTCoreTextLayouter alloc] initWithAttributedString:attributedString];
    NSRange entireString = NSMakeRange(0, [attributedString length]);
    //获取Frame
    DTCoreTextLayoutFrame *layoutFrame = [layouter layoutFrameWithRect:_viewMaxRect range:entireString];
    //得到大小
    CGSize sizeNeeded = [layoutFrame frame].size;
    
    return sizeNeeded;
}

//Html->富文本NSAttributedString
- (NSAttributedString *)getAttributedStringWithHtml:(NSString *)htmlString
{
    //获取富文本
    
    CGSize maxImageSize = CGSizeMake(self.viewMaxRect.size.width, 3300.0);
    
    NSData *data = [NSData dataWithBytes:[htmlString UTF8String] length:[htmlString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    @weakify(self);
    // example for setting a willFlushCallback, that gets called before elements are written to the generated attributed string
    void (^callBackBlock)(DTHTMLElement *element) = ^(DTHTMLElement *element) {
        
        // the block is being called for an entire paragraph, so we check the individual elements
        @strongify(self);
        [self updateCodeCSSWithDTHTMLElement:element];
    };
    //    @"Meslo LG L", DTDefaultFontFamily,@"MesloLGL-Regular"
    NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:1.0], NSTextSizeMultiplierDocumentOption,
                                    [NSValue valueWithCGSize:maxImageSize], DTMaxImageSize,
                                    @"black", DTDefaultLinkColor, callBackBlock, DTWillFlushBlockCallBack,[[NSBundle mainBundle] resourceURL],NSBaseURLDocumentOption,nil];
    
    NSAttributedString *string = [[NSAttributedString alloc] initWithHTMLData:data options:options documentAttributes:NULL];
    
    return [CSDNTool stringByTrimmingWhitespaceAndNewlineAttributedString:string];
}

- (void)updateCodeCSSWithDTHTMLElement:(DTHTMLElement *)element
{
    for (DTHTMLElement *oneChildElement in element.childNodes)
    {
        
        
        if([oneChildElement isKindOfClass:[DTTextAttachmentHTMLElement class]])
        {
            DTTextAttachment * textAttachment=oneChildElement.textAttachment;
            if ([textAttachment isKindOfClass:[DTImageTextAttachment class]] )
            {
                if(textAttachment.contentURL==nil||[textAttachment.contentURL.absoluteString isEqualToString:@""])
                {
                    NSString * srcUrl =textAttachment.attributes[@"data-src"];
                    if(srcUrl)
                    {
                        textAttachment.contentURL = [NSURL URLWithString:srcUrl];
                    }
                    else
                    {
                        textAttachment.originalSize = CGSizeZero;
                        continue;
                    }
                }
                if(CGSizeEqualToSize(textAttachment.originalSize, CGSizeZero))
                {
                    if ([textAttachment.contentURL.absoluteString containsString:@"forum.csdn.net/PointForum/ui/scripts/csdn/Plugin"] || [textAttachment.contentURL.absoluteString containsString:@"g.csdnimg.cn/static/face/"])
                    {
                        textAttachment.originalSize = CGSizeMake(25, 25);
                    }
                    else
                    {
                        
                        if (![[NSUserDefaults standardUserDefaults] objectForKey:textAttachment.contentURL.absoluteString])
                        {
                            //这里拿到每个图片的尺寸，然后计算出每个cell的高度
                            CGSize imageSize = [UIImage getImageSizeWithURL:textAttachment.contentURL];
                            CGFloat imgH = 0;
                            if (imageSize.height > 0)
                            {
                                //这里就把图片根据 固定的需求宽度  计算 出图片的自适应高度
                                CGFloat imgSizeScale = imageSize.height/imageSize.width;
                                CGFloat widthPx = _viewMaxRect.size.width;
                                imgH = widthPx * imgSizeScale;
                            }
                            //将最终的自适应的高度 本地化处理
                            [[NSUserDefaults standardUserDefaults] setObject:@(imgH) forKey:textAttachment.contentURL.absoluteString];
                            [[NSUserDefaults standardUserDefaults] synchronize];
                        }
                        CGFloat heightPx = [[[NSUserDefaults standardUserDefaults] objectForKey:textAttachment.contentURL.absoluteString] floatValue];
                        textAttachment.originalSize= CGSizeMake(_viewMaxRect.size.width, heightPx);
                        
                    }
                    
                }
            }
        }
        
        [self updateCodeCSSWithDTHTMLElement:oneChildElement];
    }
    
}

- (void)dealloc
{
    
}


@end
